package com.ddpaysdk;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.alipay.sdk.app.PayTask;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import java.util.Map;

import androidx.annotation.NonNull;

public class RNAliPayModule extends ReactContextBaseJavaModule {
    private Callback jCallBack;

    public RNAliPayModule(ReactApplicationContext reactContext){

    }
    @NonNull
    @Override
    public String getName() {
        return "aliPay";
    }
    @ReactMethod
    public void pay(final String orderInfo, final String scheme, Callback callBack){
        //scheme 只是为了让pay方法与ios 统一
        jCallBack = callBack;
        Runnable payRunnable = new Runnable() {


            public void run() {
                PayTask alipay = new PayTask(getCurrentActivity());
                Map<String, String> result = alipay.payV2(orderInfo,true);
                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                {

                    if(jCallBack != null && msg != null){
                        Map<String, String> result = (Map<String, String>)msg.obj;
                        String resultStatus = "0";
                        if (result.containsKey("resultStatus")){
                            resultStatus = result.get("resultStatus");
                        }
//                        String results = result.get("result");
                        jCallBack.invoke(null, resultStatus);
                        jCallBack = null;
                    }
                }
                break;

                default:
                    break;
            }

        };
    };
}
